﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TimKen.BussLogic;
using System.Data;
using TimKen.App;
using System.Text;
using TimKen.DataEntity;
using System.IO;
using TimKen.DataAccess;
using System.Data.SqlClient;

namespace TimKen.Web
{
    public partial class ProductInfo : TimKen.App.WebPage
    {
        public PCategoryManager pcm = new PCategoryManager();
        public DataEntity.Product product;
        public TimKen.DataEntity.PDescription description;


        public ProductManager productManager = new ProductManager();
        private PDescriptionManager descriptionManager = new PDescriptionManager();
        private PAttributeManager attributeManager = new PAttributeManager();
        public int ProductID;
        public string ProductInfoUrl;


        public DataRowCollection drcUncel;

        public string parentLink;


        /// <summary>
        /// 分类ID
        /// </summary>
        public int CategoryID
        {
            get
            {
                if (ViewState["CategoryID"] != null)
                    return Convert.ToInt32(ViewState["CategoryID"]);
                else
                    return 0;
            }
            set
            {
                ViewState["CategoryID"] = value;
            }
        }

        /// <summary>
        /// 品牌ID
        /// </summary>
        public int brandID
        {
            get
            {
                if (ViewState["brandID"] != null)
                    return Convert.ToInt32(ViewState["brandID"]);
                else
                    return 0;
            }
            set
            {
                ViewState["brandID"] = value;
            }
        }




        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["CategoryID"] != null)
            {
                CategoryID = int.Parse(Request.QueryString["CategoryID"]);
            }


            if (Request.QueryString["ProductID"] != null && TypeParse.IsNumeric(Request.QueryString["ProductID"]))
            {
                ProductID = Convert.ToInt32(Request.QueryString["ProductID"]);
                ProductInfoUrl = GetProductImage(Convert.ToInt32(ProductID));
            }
            else
            {
                Response.Redirect("/Error.aspx");
            }

            BindData();

            if (!Page.IsPostBack)
            {
                //BindResources();
                BindDownLoad();


                if (string.IsNullOrEmpty(Request.QueryString["brandid"]) || !TypeParse.IsNumeric(Request.QueryString["brandid"]))
                {
                    brandID = 0;
                }
                else
                    brandID = int.Parse(Request.QueryString["brandid"]);
                
                //@"<a href='产品页面1.html'>产品分类</a> - <a href='产品页面2.html'>链条</a> —<a href='产品页面列表页面.html'>Renold 滚子链</a> — Renold 链条";// WebPage.GetCategoryListSite;
            }
            if (CategoryID != 0)
            {
                PCategoryManager pcm = new PCategoryManager();
                parentLink = GetParentLink(pcm.GetAllParent(CategoryID, LanguageID));
            }
        }

        private string GetParentLink(string linkData)
        {
            string[] links = linkData.Split(',');
            StringBuilder sb = new StringBuilder();
            if (links.Length > 0)
            {
                sb.Append("<a href=\"Category.aspx?\">" + GetLangString("ProductCategories") + "</a>&nbsp;—&nbsp;");


                for (int i = 0; i < links.Length; i++)
                {
                    string link = links[i];
                    string[] nameid = link.Split(':');

                    if (nameid.Length == 2 && i != links.Length - 1)
                    {
                        sb.Append("<a href=\"ChildCategory.aspx?cid=" + nameid[1] + "&brandid=" + brandID + "\">" + nameid[0] + "</a>&nbsp;—&nbsp;");
                    }
                    else
                    {
                        sb.Append(nameid[0] + "&nbsp;—&nbsp;");
                    }
                }
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 7, 7);
            }
            return sb.ToString();
        }


        private DataTable ReturnResourceTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("FileName", typeof(string));
            dt.Columns.Add("FileSize", typeof(long));
            dt.Columns.Add("DownLoad", typeof(string));

            if (!string.IsNullOrEmpty(product.IntroDocFiles))
            {
                string[] files = product.IntroDocFiles.Split(',');
                for (int i = 0; i < files.Length; i++)
                {
                    string file = files[i];
                    DataRow newRow = dt.NewRow();
                    newRow["FileName"] = file;
                    newRow["FileSize"] = GetSizeByName(UploadFilePathForProduct + file);
                    newRow["DownLoad"] = GetLangString("Download");
                    dt.Rows.Add(newRow);
                }
            }
            return dt;
        }
        ///// <summary>
        ///// 绑定多语言资源
        ///// </summary>
        //protected void BindResources()
        //{
        //    btnAddToShoppingCart.ToolTip = GetLangString("AddToShoppingCart");
        //    btnFavorite.ToolTip = GetLangString("AddToFavorite");
        //}

        private void BindDownLoad()
        {
            //新增绑定下载资源
            repResource.DataSource = ReturnResourceTable();
            repResource.DataBind();
        }

        //private void BindCommonLst()
        //{ 
        //    //绑定评论
        //    int productId = Convert.ToInt32( HttpContext.Current.Request["ProductID"]);
        //    SqlParameter[] parameters = {
        //            new SqlParameter("@PageSize", SqlDbType.Int),
        //            new SqlParameter("@PageIndex", SqlDbType.Int),
        //            new SqlParameter("@ProductID", SqlDbType.Int)
        //            };
        //    parameters[0].Value = this.AspNetPager1.PageSize;
        //    parameters[1].Value = this.AspNetPager1.CurrentPageIndex;
        //    parameters[2].Value = productId;
        //    DataSet ds =DbHelperSQL.RunProcedure("Proc_Get_PComment_List",parameters,"ds");
        //    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
        //    {
        //        repMessageLst.DataSource = ds;
        //        repMessageLst.DataBind();
        //        this.AspNetPager1.RecordCount = ds.Tables[0].Rows.Count;
        //        HiddCommons.Value = ds.Tables[0].Rows.Count.ToString();
        //    }
        //}

        //protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        //{
        //    BindCommonLst();
        //}

        private void BindData()
        {
            product = productManager.GetModel(ProductID);
            description = descriptionManager.GetModel(ProductID, LanguageID);

            divdh.InnerHtml = GetCategoryListSite(Convert.ToInt32(product.CategoryID), Convert.ToInt32(product.BrandID));
            if (product == null || description == null)
                Response.Redirect("/Error.aspx", true);

            PCategoryManager pcm = new PCategoryManager();
            DataSet ds = pcm.GetUncle(product.CategoryID.Value, LanguageID);

            if (ds != null)
            {                            
                dlCategory.DataSource = ds;
                dlCategory.DataBind();
            }

        }

        protected void btnAddToShoppingCart_Click(object sender, ImageClickEventArgs e)
        {
            UserS u = Session["User"] as UserS;

            //如果用户未登陆，则跳转到注册页面
            if (u == null)
                Response.Redirect("/User/Register.aspx");

            //如果是自注册用户，提示申请成为正式用户
            if (u.UserType == UserType.SelfRegistered)
            {
                Response.Redirect("/ErrorAuthority.aspx");
            }
            else
            {
                //判断购买数量是否有效
                decimal number = 50;
                if (!decimal.TryParse(txtNumber.Text, out number) || number < 0)
                {
                    Alert(GetLangString("InValidNumber"));
                    return;
                }
                ShoppingCartManager scm = new ShoppingCartManager();
                ShoppingCart model = new ShoppingCart();

                model.UserName = CurrentUserName;
                model.Number = number;
                model.ProductID = ProductID;
                if (GetProductBasePrice(ProductID).Price == 0)
                {
                    Alert(GetLangString("Price0Product"));
                    return;
                }
                DataEntity.Product product = productManager.GetModel(ProductID);



                //2009-3-30 修改成库存为空也可以下单

                //if (product.InvQty - product.BookedQty - number < 0)
                //{
                //    Alert(GetLangString("NotEnoughInventory"));
                //    return;
                //}

                /*
                if (scm.Exists(model.UserName, model.ProductID))
                {
                    Alert(GetLangString("ProductInShoppingCart"));
                    return;
                }
                else
                {*/
                scm.Add(model);

                //Top top = this.Page.Master.FindControl("Top1") as Top;
                //top.totalCartCount = top.totalCartCount + number;
                //Alert(GetLangString("AddProductSuccessful"));
                //}
            }

        }

        protected void btnFavorite_Click(object sender, ImageClickEventArgs e)
        {
            //如果用户未登陆，则跳转到注册页面
            if (CurrentUserName == null)
                Response.Redirect("/User/Register.aspx");


            FavoriteManager favorM = new FavoriteManager();
            TimKen.DataEntity.Favorite model = new TimKen.DataEntity.Favorite();

            model.ProductID = ProductID;
            model.DateAdded = DateTime.Now;
            model.UserName = CurrentUserName;
            favorM.Add(model);
            Alert(GetLangString("AddSuccessful"));
        }

        //protected void ImageBtnCommon_Click(object sender, ImageClickEventArgs e)
        //{
        //    //如果用户未登陆，则跳转到注册页面
        //    string productId = HttpContext.Current.Request["ProductID"];
        //    string content = txtCommons.Text;

        //    string CurrentUserName = Session["User"] == null ? "未注册" : ((UserS)Session["User"]).UserName;
        //    string sql = "INSERT  PComment(Creator,[Content],ProductID)  VALUES ('{0}','{1}',{2})";
        //    sql = string.Format(sql, CurrentUserName, content, productId);
        //    DbHelperSQL.ExecuteSql(sql);
        //    BindCommonLst();
        //}

        public string SetInventoryString(decimal inventory)
        {
            if (inventory <= 0)
            {
                return GetLangString("UnavailableIvq");
            }
            else
            {
                return GetLangString("AvailableIvq");
            }
        }


        public long GetSizeByName(string path)
        {

            FileInfo file = new FileInfo(Server.MapPath(path));


            string key = "file" + path;
            object size = Cache.Get(key);

            if (size == null)
            {
                if (!file.Exists)
                    size = 0;
                else
                    size = file.Length;
                Cache.Insert(key, size);
                return long.Parse(size.ToString());
            }
            return long.Parse(size.ToString());
        }

        protected void repResource_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Down")
            {
                try
                {

                    //string path = UploadFilePathForProduct + e.CommandArgument.ToString();//10月23客户邮件要求更换地址
                    string path = UploadFilePathForResource + e.CommandArgument.ToString();
                    string filename = System.IO.Path.GetFileName(e.CommandArgument.ToString());
                    if (System.IO.File.Exists(Server.MapPath(path)))
                    {
                        string filePath = Server.MapPath(path);//路径 
                        //以字符流的形式下载文件 
                        FileStream fs = new FileStream(filePath, FileMode.Open);
                        byte[] bytes = new byte[(int)fs.Length];
                        fs.Read(bytes, 0, bytes.Length);
                        fs.Close();
                        Response.ContentType = "application/octet-stream";
                        //通知浏览器下载文件而不是打开 
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
                        Response.BinaryWrite(bytes);
                        Response.Flush();
                        Response.End();
                    }
                    else
                    {
                        Alert(GetLangString("NotFoundFile"));
                    }
                }
                catch
                {
                    Response.Redirect("/Error.aspx");
                }
            }
        }
        public string returnProdName(string str)
        {
            if (str.Length > 12)
            {
                return str.Substring(0, 10) + "...";
            }
            return str;
        }
        public string returnName(string strName)
        {
            if (LanguageID == 1) //中文
            {
                if (strName.Length > 11)
                {
                    return strName.Substring(0, 12) + "...";
                }
                else
                {
                    return strName;
                }
            }
            else//英文 
            {
                if (strName.Length > 19)
                {
                    return strName.Substring(0, 18) + "...";
                }
                else
                {
                    return strName;
                }
            }
        }
    }
}